package com.pdool.game.logic.handler.card;

import com.pdool.common.constants.ErrorCode;
import com.pdool.common.constants.MsgId;
import com.pdool.common.dict.CardInfoConfigVo;
import com.pdool.common.entity.CardInfoEntity;
import com.pdool.common.exception.ErrorException;
import com.pdool.common.msg.card.CardLvUpReq;
import com.pdool.common.msg.card.CardLvUpResp;
import com.pdool.game.core.msg.IHandler;
import com.pdool.game.core.msg.MsgHandler;
import com.pdool.game.core.res.ResOp;
import com.pdool.game.dict.CardConfig;
import com.pdool.game.logic.service.CardService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Map;

/**
 * 卡牌升级
 */
@Component
@MsgHandler(MsgId.CARD_UP_LV)
public class UpLvHandler implements IHandler<CardLvUpReq, CardLvUpResp> {
    @Resource
    CardConfig cardConfig;
    @Resource
    CardService cardService;

    @Override
    public CardLvUpResp handle(Long roleId, CardLvUpReq cardLvUpReq) {
        int cardId = cardLvUpReq.getCardId();

        Map<Integer, CardInfoEntity> allCardMap = cardService.getAllCard(roleId);
        CardInfoEntity cardInfoEntity = allCardMap.get(cardId);
        if (cardInfoEntity == null) {
            throw new ErrorException(ErrorCode.NOT_EXIST_CARD);
        }
        CardInfoConfigVo config = cardConfig.getByKey(cardId);

        Map<Integer, String> levelCost = config.getLevelCost();

        int maxLv = Collections.max(levelCost.keySet());
        if (maxLv == cardInfoEntity.getLv()) {
            throw new ErrorException(ErrorCode.CARD_HAS_MAX_LV);
        }
        String cost = config.getLevelCost().get(cardInfoEntity.getLv() + 1);

        ResOp resOp = new ResOp(roleId);
        resOp.cost(cost);
        if (!resOp.op()) {
            if (maxLv == cardInfoEntity.getLv()) {
                throw new ErrorException(ErrorCode.CARD_HAS_MAX_LV);
            }
        }
        cardInfoEntity.setLv(cardInfoEntity.getLv() + 1);
        cardService.updateCard(allCardMap, cardInfoEntity);

        CardLvUpResp.Builder builder = CardLvUpResp.newBuilder();
        builder.setCardId(cardId);
        builder.setLv(cardInfoEntity.getLv());

        return builder.build();
    }
}